//
//  UIlabel+Extension.swift
//  JKCAGradientLayer
//
//  Created by IronMan on 2021/2/1.
//

import Foundation

public enum JKViewGradientDirection {
    /// 水平从左到右
    case horizontal
    ///  垂直从上到下
    case vertical
    /// 左上到右下
    case leftOblique
    /// 右上到左下
    case rightOblique
    /// 请他情况
    case other(CGPoint, CGPoint)
    
    public func point() -> (CGPoint, CGPoint) {
        switch self {
        case .horizontal:
            return (CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0))
        case .vertical:
            return (CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 0))
        case .leftOblique:
            return (CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 1))
        case .rightOblique:
            return (CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 1))
        case .other(let stat, let end):
            return (stat, end)
        }
    }
}

extension UILabel {
    
    /// 设置文字的颜色渐变
    /// - Parameters:
    ///   - direction: 渐变的方向
    ///   - gradientColors: 渐变的颜色数组
    ///   - gradientLocations: 渐变颜色所在的位置
    func textGradient(_ direction: JKViewGradientDirection = .horizontal, _ gradientColors: [Any], _ gradientLocations: [NSNumber]? = nil) {
        
        guard let labelSuperview = superview else {
            return
        }
        // 创建用于放置文本标签和渐变层的view
        let container = UIView(frame: self.frame)
        labelSuperview.addSubview(container)
      
        // 创建CAGradientLayer对象并设置参数
        let gradientLayer = CAGradientLayer()
        // 定义渐变的颜色（从黄色渐变到橙色）
        gradientLayer.colors = gradientColors
        // 定义每种颜色所在的位置
        gradientLayer.locations = gradientLocations
        // 设置渲染的起始结束位置（渐变方向设置）
        gradientLayer.startPoint = direction.point().0
        gradientLayer.endPoint = direction.point().1
        
        // 设置其CAGradientLayer对象的frame，并插入container的layer
        gradientLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        container.layer.insertSublayer(gradientLayer, at: 0)
        
        // 将渐变层的遮罩设置为label
        gradientLayer.mask = self.layer
    }
}
